<?php

namespace App\Jobs;

use App\Image;
use App\Show;
use GuzzleHttp\Client;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Symfony\Component\DomCrawler\Crawler;

class FetchTtmjShowDetail extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    protected $show;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($show)
    {
        var_dump($show);
        $this->show = $show;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if ($this->attempts() > 1) {
            $this->delete();
            return;
        }
        $base_url = 'http://www.ttmeiju.com';
        $header_params = config('app.google_bot_headers');
        $header_params['referer'] = 'bbs.ttmeiju.com';

        //获取登陆cookie
        $client = new Client([
            'headers' => $header_params,
            'cookies' => true,
            'allow_redirects' => true,
            'base_uri' => $base_url,
            'http_errors' => false,
        ]);
        $uri = $this->show->url_provider;

        $res = $client->request('GET',$uri);

        if ($res->getStatusCode() != 200) {
            \Log::alert('获取美剧详情' . $uri);
            return;
        }

        $dom = $res->getBody()->getContents();
        $crawler = new Crawler($dom);

        $image_url = $crawler->filter('#spic')->first()->attr('src');
        $detail_text = $crawler->filter('div.newstxt')->first()->html();
        $time = date('y_md_his');
        $key = "ttmj{$this->show->name_en} {$time}";
        $img = Image::fetchUrlWithKey($image_url,$key,$this->show->name_en);

        $show = Show::find($this->show->id);
        $show->timestamps = false;
        $show->update(['detail'=>$detail_text]);
        if ($img->id > 0) {
            $show->images()->save($img);
        }

    }
}
